﻿
using System;

namespace GNUGo.Net.CLI {
    public class CliUserInterface : UserInterface {
        private GoGame _game;
        private bool _exit;
        private readonly CliGoForm _goForm;

        public CliUserInterface() {
            _goForm = new CliGoForm();
        }

        public override GoGame Game {
            get { return _game; }
        }

        public override void NewGame(int size) {
            _game = new GoGame(size);
            _goForm.Game = _game;
        }

        public void PlayGame() {
            _exit = false;
            while (!_exit) {
                string command = _goForm.Prompt.ReadLine();
                ProcessCommand(command);
            }
        }

        public override void DoExit() {
            _exit = true;
            base.DoExit();
        }

        private void ProcessCommand(string command) {
            command = command.Trim();
            switch (command) {
                case "exit":
                case "quit":
                    DoExit();
                    break;
                default:
                    string message = string.Format("Invalid command '{0}'", command);
                    int x, y;
                    if (Intersection.TryParse(command, out x, out y)) {
                        try {
                            message = "";
                            Game.Play(x, y);
                        }
                        catch (GoException ex) {
                            message = ex.Message;
                        }
                    }
                    _goForm.MessageLabel.Text = message;
                    break;
            }
        }
    }
}
